
<template>
  <main>
    <h1>注册页面</h1>


    <form id="payment-form" @submit.prevent="handleSubmit">
      <div>
        <label for="name">名字</label>
        <input id="name">
      </div>

      <div>
        <label for="email">邮箱</label>
        <input id="email">
      </div>
      
      <button
        id="submit"
        :disabled="isLoading"
      >
        注册
      </button>
      <sr-messages :messages="messages" />
    </form>
    <div>
        <a href="/login">有账号去登录</a>
    </div>
  </main>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { loadStripe } from "@stripe/stripe-js";

import SrMessages from "./SrMessages.vue";

const isLoading = ref(false);
const messages = ref([]);


const handleSubmit = async () => {
  if (isLoading.value) {
    return;
  }

  isLoading.value = true;
  const nameInput = document.querySelector('#name');
  const emailInput = document.querySelector('#email');
  console.log(nameInput.value, '***', emailInput.value)
  await fetch(
      '/api/user/registry',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: nameInput.value,
          email: emailInput.value,
        }),
      }
    ).then((r) => {
      console.log('第一个then', r)
      return r.json()
    }).then((r) => {
      //{"code":200,"data":{"name":"an","id":3,"stripeCustomerId":"cus_PTbTKK6AOYHRn7","email":"qwe@163.com"},"message":"SUCCESS"}
      console.log('第二个then', r)
      if (r.code == 200) {
        sessionStorage.setItem('id', r.data.id)
        sessionStorage.setItem('name', r.data.name)
        sessionStorage.setItem('email', r.data.email)
        sessionStorage.setItem('stripeCustomerId', r.data.stripeCustomerId)
        window.location.href = '/'; 
      }
    });

  // const { error } = await stripe.confirmPayment({
  //   elements,
  //   confirmParams: {
  //     return_url: `${window.location.origin}/return`
  //   }
  // });

  // if (error.type === "card_error" || error.type === "validation_error") {
  //   messages.value.push(error.message);
  // } else {
  //   messages.value.push("An unexpected error occured.");
  // }

  isLoading.value = false;
}
</script>